package com.rolerealm.service.impl;

import com.rolerealm.dao.UserInteractionMapper;
import com.rolerealm.domain.entity.UserInteractionEntity;
import com.rolerealm.domain.vo.UserInteractionVO;
import com.rolerealm.service.UserInteractionService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户行为数据收集服务Mock实现（临时使用，用户管理模块完成后将被替换）
 * 
 * @author RoleRealm Team
 * @version 1.0.0
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class MockUserInteractionServiceImpl implements UserInteractionService {

    private final UserInteractionMapper userInteractionMapper;

    @Override
    public void recordUserInteraction(Long userId, Long characterId, String interactionType, Integer durationSeconds) {
        log.debug("记录用户行为，用户ID：{}，角色ID：{}，交互类型：{}，时长：{}秒", 
                userId, characterId, interactionType, durationSeconds);
        
        UserInteractionEntity entity = UserInteractionEntity.builder()
                .userId(userId)
                .characterId(characterId)
                .interactionType(interactionType)
                .durationSeconds(durationSeconds)
                .createdAt(LocalDateTime.now())
                .build();
        
        try {
            userInteractionMapper.insert(entity);
            log.debug("用户行为记录成功");
        } catch (Exception e) {
            log.error("用户行为记录失败", e);
        }
    }

    @Override
    public List<UserInteractionVO> getUserInteractions(Long userId, Integer days) {
        log.debug("获取用户行为数据，用户ID：{}，最近天数：{}", userId, days);
        
        // 查询用户最近N天的行为数据
        LocalDateTime startTime = LocalDateTime.now().minusDays(days);
        List<UserInteractionEntity> entities = userInteractionMapper.selectByUserIdAndTimeRange(userId, startTime);
        
        return entities.stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
    }

    /**
     * 转换为用户行为VO
     */
    private UserInteractionVO convertToVO(UserInteractionEntity entity) {
        UserInteractionVO vo = new UserInteractionVO();
        BeanUtils.copyProperties(entity, vo);
        return vo;
    }
}
